<!DOCTYPE HTML>
<html>
	<head>
		<title>HTML5 Video Browser</title>
		<script>
			var resolver = false;
			var html5video = true;

			function list(url){
				l0.innerHTML = 'loading ' + decodeURIComponent(url) + ' ...';
				xhr("GET", url, null, function(r){
					var l1 = r.match(/<a href="[^"]+">/g);
					var l2 = ['browsing: ' + decodeURIComponent(url)];
					for (var i = 0; i < l1.length; ++i){
						var e = l1[i];
						e = e.slice(9, e.length - 2);
						if(e.charAt(e.length - 1) == '/'){
							if(e == '../'){
								var link = url.slice(0, url.lastIndexOf('/', url.length - 2) + 1);
							}else{
								link = url + e;
							}
							if(link.length > 0){
								l2.push('<a onclick="list(\'' + link+ '\')">'
									+ decodeURIComponent(e) + '</a>');
							}
						}else if((!html5video) || e.slice(-4).toLowerCase() == ".mp4"){
							l2.push('<a onclick="resolve(\'' + url + e + '\')">'
								+ decodeURIComponent(e) + '</a>');
						}
					}
					l0.innerHTML = l2.join('<br>');
				});
			}

			function xhr(method, url, data, callback){
				var x = new XMLHttpRequest();
				x.onreadystatechange = function(){
					//TODO: exception handling
					if(x.readyState == 4 && x.status == 200){
						callback(x.responseText);
					}
				}
				x.open(method, url, true);
				x.send(data);
			}

			function ua_detect(){
				for(var i = 0; i < arguments.length; ++i){
					if(navigator.userAgent.indexOf(arguments[i]) != -1){
						return true;
					}
				}
				return false;
			}

			function resolve(url){
				if(resolver){
					xhr("POST", resolver, url, function(r){
						play(r);
					});
				}else{
					play(url);
				}
			}

			function play(url){
				if(html5video){
					v0.src = url;
				}else{
					var link = document.createElement("a");
					link.setAttribute("href", url);
					link.click();
				}
			}

			window.onload = function(){
				// d0.innerHTML = JSON.stringify(navigator, ["userAgent", "platform", "vendor"], "\t");
				xhr("GET", "config.json", null, function(r){
					// d0.innerHTML = r;
					var config = JSON.parse(r);
					var bl = [];
					for(var i in config.buttons){
						bl.push("<button onclick=\"list('" + config.buttons[i] + "')\">"
							+ i + "</button>");
					}
					bl0.innerHTML = bl.join("\n");
					// currently targeting 3 platforms
					// iOS does not need secdownload, use html5 video
					// PlayStation needs secdownload, use html5 video
					// Android needs secdownload, use mx player instead of html5video
					if (ua_detect("Android")){
						resolver = config.resolver;
						html5video = false;
					}else if (ua_detect("PlayStation")){
						resolver = config.resolver;
						html5video = true;
					}else{
						resolver = false
						html5video = false;
					}
				});
			}
		</script>
	</head>

	<body>

	<video id="v0" oncanplay="play()" controls>
		video tag not supported on your browser
	</video>

	<div id="bl0">
	</div>

	<div id="d0">
	</div>

	<div id="l0">
	</div>

	</body>
</html>
